import sys,os
import pyfaidx


def format_seq(seq, wrap):
    seq = seq.upper()
    chunks = [seq[i:i+wrap] for i in range(0, len(seq), wrap)]
    return "\n".join(chunks) + "\n"

def orderfasta(infasta, agp, outfasta):
    inf = pyfaidx.Fasta(infasta)
    out = open(outfasta, 'w')
    dic = {}
    for i in open(agp):
        if i.startswith('AcHBChr'):
            tmp = i.strip().split()
            chrom = tmp[0]
            order = tmp[-1]
            if order == "+":
                seq = str(inf[chrom][0:].seq)
                seq = format_seq(seq, 80)
                out.write(f">{chrom}\n{seq}")
            else:
                seq = str(inf[chrom][0:].reverse.complement.seq)
                seq = format_seq(seq, 80)
                out.write(f">{chrom}\n{seq}")
        else:
            tmp = i.strip().split()
            chrom = tmp[0]
            order = tmp[-1]
            seq = str(inf[chrom][0:].seq)
            seq = format_seq(seq, 80)
            out.write(f">{chrom}\n{seq}")


if __name__ == '__main__':
    infasta = sys.argv[1]
    agp = sys.argv[2]
    outfasta = sys.argv[3]
    orderfasta(infasta, agp, outfasta)


